package com.naton.mydemo.model.dao

import android.annotation.SuppressLint
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.*
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery
import com.naton.common.ui.CommApplication.getInstance
import com.naton.mydemo.bean.ChatMessage
import com.naton.mydemo.model.dao.AppDataBase
import com.naton.mydemo.ui.MyApplication

/**
 * @time: 2022/3/4
 * @author: lifuling
 * @version: v1.0
 * @file_desc:
 */
@Dao
abstract class ChatMessageDao {

    fun insert(tableName: String, chatMessage: ChatMessage?) {
        val contentValues = ContentValues()
        contentValues.put("msgId", chatMessage?.msgId)
        contentValues.put("content", chatMessage?.content)
        AppDataBase.getDataBase().openHelper.writableDatabase.insert(
            tableName,
            SQLiteDatabase.CONFLICT_REPLACE,
            contentValues
        )
    }

    fun createTable(tableName: String) {
        val sql = "create table IF NOT EXISTS [$tableName]  ( msgId VARCHAR  PRIMARY KEY , content VARCHAR)"
        AppDataBase.getDataBase().openHelper.writableDatabase.execSQL(sql)
    }

    fun queryChatMessageById(tableName: String , msgId : String): ChatMessage{
        val query = SimpleSQLiteQuery("select * from $tableName where msgId = ?" , arrayOf(msgId) )
        return doFindOne(query)
    }

    fun getTableName(toUserId : String) : String{
        return toUserId + "_"
    }

    @RawQuery
    abstract fun doFindOne(query: SupportSQLiteQuery?): ChatMessage

    @RawQuery
    abstract fun doFindAll(query: SupportSQLiteQuery?): List<ChatMessage>

}